#  This code is part of cqlib.
#  #
#  (C) Copyright qc.zdxlz.com 2024.
#  #
#  This code is licensed under the Apache License, Version 2.0. You may
#  obtain a copy of this license in the LICENSE.txt file in the root directory
#  of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#  #
#  Any modifications or derivative works of this code must retain this
#  copyright notice, and modified files need to carry a notice indicating
#  that they have been altered from the originals.
#
import pytest
from pathlib import Path
import os
from cqlib import GuoDunPlatform
from cqlib.utils import QasmToQcis
from cqlib.mapping import transpile_qcis

test_qasm_file = list(Path('./benchmark').iterdir())
login_key = os.getenv('LOGIN_KEY')
sim_machine = os.getenv('SIM_MACHINE')
quantum_machine = os.getenv('QUANTUM_MACHINE')


@pytest.fixture
def platform():
    """
    Fixture to create an instance of the GuoDunPlatform class
    """
    if scheme := os.getenv('SCHEME'):
        GuoDunPlatform.SCHEME = scheme
    if domain := os.getenv('DOMAIN'):
        GuoDunPlatform.DOMAIN = domain
    assert login_key, 'Please set the login key first'
    assert sim_machine, 'Please set the simulator code first'
    # assert quantum_machine, 'Please set the quantum computer code first'

    return GuoDunPlatform(login_key=login_key, machine_name='gd_qc1')


def qasm_to_qcis(qasm_file: Path):
    qcis_circuit = QasmToQcis().convert_to_qcis_from_file(qasm_file)
    return qcis_circuit


@pytest.mark.parametrize("qasm_file", test_qasm_file)
@pytest.mark.timeout(120)
def test_qasm_cases(qasm_file: Path, platform):
    qcis_circuit_before_mapping = QasmToQcis().convert_to_qcis_from_file(qasm_file)
    qcis_circuit, initial_layout, swap_mapping, mapping_virtual_to_final = transpile_qcis(qcis_circuit_before_mapping, platform)
    qcis_after_mapping = qcis_circuit.qcis.upper()
    assert qcis_after_mapping
    qcis_check_rule = platform.qcis_check_regular(qcis_after_mapping)
    assert qcis_check_rule

